package chuangyi.com.org.DOMIHome.Utils;

import android.content.Context;
import android.net.Uri;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

/**
 * Created by zxh on 16/11/28.
 */

public class OSSUtil {
    static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    static final String KEY_SECRET = "BYCVwyugs85hWyRTYx65ToSaOaXFDL";
    static final String KEY_ID = "LTAI6hvuJxtnmjG8";
    static final String BUCKET_NAME = "dmyjr";
    static final OSSCredentialProvider credentialProvider;

    static {
        credentialProvider = new OSSPlainTextAKSKCredentialProvider(KEY_ID, KEY_SECRET);
    }

    public static OSSClient getClient(Context applicationContext) {
        return new OSSClient(applicationContext, ENDPOINT, credentialProvider);
    }

    public static String uploadFile(OSSClient oss, String fileName) {
        String objectKey = UUID.randomUUID().toString() + Utils.getFileExtension(fileName);
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, objectKey, fileName);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.addUserMetadata("x-oss-process", "image/resize,w_600");
        put.setMetadata(metadata);
        try {
            oss.putObject(put);
            return oss.presignPublicObjectURL(BUCKET_NAME, objectKey);
        } catch (Exception ex) {
            return null;
        }
    }

    public static String uploadFile(Context applicationContext, String fileName) {
        OSSClient oss = getClient(applicationContext);
        GetObjectRequest result;
        String objectKey = UUID.randomUUID().toString() + "." + Utils.getFileExtension(fileName);
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, objectKey, fileName);
        try {
            oss.putObject(put);
            return oss.presignPublicObjectURL(BUCKET_NAME, objectKey);
        } catch (Exception ex) {
            return null;
        }
    }

    public static boolean downloadFile(Context applicationContext, String url, String path) {
        File file = new File(path);
        return downloadFile(applicationContext, url, file);
    }

    public static boolean downloadFile(Context applicationContext, String url, File file) {
        OSSClient ossClient = getClient(applicationContext);
        // 下载object到文件  new File("<yourLocalFile>"这个file对象需要给定一个本地目录，文件会下载到该目录中
        try {
//            String name =Utils.getFileName(url);
//            Uri uri = Uri.parse(url);
//            String name = uri.getEncodedPath().substring(1);
//            GetObjectResult result = ossClient.getObject(new GetObjectRequest(BUCKET_NAME, name));
//            if (result.getStatusCode() == 200 || result.getStatusCode() == 206) {
//                InputStream stream = result.getObjectContent();
//                if(file.exists() == false){
//                    file.createNewFile();
//                }
//                FileOutputStream fileOutputStream = new FileOutputStream(file, false);
//                byte[] buffer = new byte[(int)result.getContentLength()];
//                fileOutputStream.write(buffer);
//                fileOutputStream.flush();
//                fileOutputStream.close();
//                return true;
//            }
            //如果目标文件已经存在，则删除。产生覆盖旧文件的效果
            if (file.exists()) {
                file.delete();
            }
            try {
                // 构造URL
                URL uri = new URL(url);
                // 打开连接
                URLConnection con = uri.openConnection();
                //获得文件的长度
                int contentLength = con.getContentLength();
                System.out.println("长度 :" + contentLength);
                // 输入流
                InputStream is = con.getInputStream();
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流
                OutputStream os = new FileOutputStream(file);
                // 开始读取
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                os.flush();
                // 完毕，关闭所有链接
                os.close();
                is.close();

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

//    public static String uploadFile(Context applicationContext, File file){
//        try {
//            String fileName = Utils.getMd5ByFile(file);
//
//        }catch (Exception ex){
//            return null;
//        }
//
//    }
}
